<template>
    <span v-if="!truncatedContent">{{ label }}</span>

    <el-tooltip v-else effect="dark" :content="label" placement="top">
        <span class="text-truncate">
            {{ truncatedContent }}
        </span>
    </el-tooltip>
</template>


<script setup>
import { computed } from 'vue'

const props = defineProps({
    label: [String, Number],
    max: {
        type: Number,
        default: 10,
        validator: value => value >= 0
    },
    rule: {
        type: String,
        default: 'end',
        validator: value => ['start', 'center', 'end'].includes(value)
    },
    symbol: {
        type: String,
        default: '...'
    }
})

const RULE = {
    start: (max, symbol) => {
        const reg = new RegExp('.+(.{' + max + '})')
        return value => (symbol || '') + value.replace(reg, '$1')
    },
    center: (max, symbol) => {
        const size = Math.floor(max / 2)
        const reg = new RegExp('^(.{' + size + '}).+(.{' + size + '})$')
        return value => value.replace(reg, `$1${symbol}$2`)
    },
    end: (max, symbol) => {
        const reg = new RegExp('^(.{' + max + '}).*')
        return value => value.replace(reg, `$1${symbol}`)
    }
}

const truncatedContent = computed(() => {
    const text = String(props.label || '')
    if (text.length <= props.max) return null

    const truncateFn = RULE[props.rule]?.(props.max, props.symbol) || RULE.end(props.max, props.symbol)
    return truncateFn(text)
})
</script>



<style scoped>
.text-truncate {
    display: inline-block;
    max-width: 100%;
    cursor: pointer;
    vertical-align: bottom;

    /* 添加CSS原生截断作为后备方案 */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* Element Plus 工具提示样式覆盖 */
:deep(.el-tooltip__trigger) {
    display: inline-block;
    width: 100%;
}
</style>